import React from "react";
import {connect} from "react-redux";
import {fetchPosts, reset} from "../../actions";
import cookie from "react-cookie";
import Events from "../../utils/Events";
import isEqual from "lodash/isEqual";
import ShopName from "../../components/ShopName";
import OrderRecordList from "../../components/OrderRecordList";
import Notifications, {notify} from "react-notify-toast";
import InputProp from "../../components/InputProp";
const PAGE_SIZE = 20;
class queryExportOrders extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            pageindex: 1,
            shopInfoList: [],
            shopOrderList: [],
            startDate: "",
            endDate: "",
            exportUnclickable: "",
            exportDisabled: "",
            shopNo: "0",
            isLoadingMore: false,
            isCanLoadMore: true,
            isShowPop: false,
            exportEmail: ""
        };
    }

    componentWillMount() {
        document.title = "查询导出订单";
    }

    componentDidMount() {
        let date = new Date();
        let curDate = dateFormat(date.getFullYear(), (date.getMonth() + 1), date.getDate());
        this.setState({
            startDate: curDate,
            endDate: curDate,
            pageindex: 1
        });
        let queryDate = cookie.load("queryDate");
        if (queryDate) {
            let {startYear, startMonth, startDay, endYear, endMonth, endDay} = queryDate;
            let startDate = dateFormat(startYear, startMonth, startDay);
            let endDate = dateFormat(endYear, endMonth, endDay);
            this.setState({
                startDate: startDate,
                endDate: endDate
            });
        }
        let shopNo = this.props.location.query.shopNo;
        if (shopNo) {
            this.setState({
                shopNo: shopNo
            })
        }
        this.queryOrderList("", this.state.pageindex);
        this.props.dispatch(reset("exportBill"));
        this._scrollListener = Events.on(window, "scroll", this.checkBottom.bind(this));
    }

    componentWillUnmount() {
        //Events.off(window, "scroll", this.checkBottom.bind(this));
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.OrderList.errorCode === 0 && this.state.pageindex == 1) {
            this.setState({
                isLoading: false
            });
            let shopInfoList = nextProps.OrderList.data.shopInfoForStaffVos;
            let shopOrderList = nextProps.OrderList.data.orderVos;
            if (shopInfoList && shopInfoList.length > 0) {
                this.setState({
                    shopInfoList: shopInfoList
                });
            }
            if (shopOrderList.length > 0) {
                this.setState({
                    exportUnclickable: "",
                    exportDisabled: ""
                });
            } else {
                this.setState({
                    exportUnclickable: "unclickable",
                    exportDisabled: "disabled"
                });
            }
            this.setState({
                shopOrderList: shopOrderList

            })
        }
        if (nextProps.OrderList.errorCode === 0 && this.state.pageindex > 1 &&
            !isEqual(nextProps.OrderList, this.props.OrderList)) {
            let shopOrderList = nextProps.OrderList.data.orderVos;
            let oldOrderList = this.state.shopOrderList;
            this.setState({
                isLoadingMore: false,
                isCanLoadMore: shopOrderList.length == PAGE_SIZE
            });
            if (shopOrderList.length > 0) {
                shopOrderList.map((item, index) => {
                    oldOrderList.push(item);
                })
            }
        }
        let myColor = {background: '#0E1717', text: "#FFFFFF"};
        if (nextProps.ExportBill.errorCode === 0) {
            notify.show("导出订单成功！", "custom", 1000, myColor);
            cookie.save("queryDate", "");
            cookie.save("queryDateType", "");
        } else if (nextProps.ExportBill.errorCode === -1) {
            let errorMessage = nextProps.ExportBill.errorMessage;
            notify.show(errorMessage, "custom", 1000, myColor);
        }
    }

    render() {
        if (this.state.isLoading) {
            return (
                <div className="loading"><span>Loading</span></div>
            );
        } else {
            return (
                <div style={{paddingTop: 20}}>
                    <Notifications/>
                    <InputProp title="" content="导出到邮箱："
                               show={this.state.isShowPop}
                               popCancel={this.popCancel.bind(this)}
                               popConfirm={this.popConfirm.bind(this)}
                    />
                    <ShopName
                        shopNames={this.state.shopInfoList}
                        shopNo={this.state.shopNo}
                        fetchDataByShopId={this.fetchOrdersByShopNo.bind(this)}
                    />
                    <div>
                        <div className="export-orders-query-date" onClick={this._changeQueryDate.bind(this)}>
                            <div>{this.state.startDate}~{this.state.endDate}</div>
                            <div><img className="export-orders-query-date-img"/></div>
                        </div>
                    </div>
                    <div className="export-orders-bottom-container">
                        <button className={this.state.exportUnclickable}
                                onClick={this._exportOrders.bind(this)}
                                disabled={this.state.exportDisabled}
                        >导出订单
                        </button>
                    </div>
                    <OrderRecordList shopOrderList={this.state.shopOrderList}/>
                </div>
            );
        }
    }

    fetchOrdersByShopNo(shopNo) {
        this.setState({
            shopNo: shopNo,
            pageindex: 1,
            isCanLoadMore: true
        });
        this.queryOrderList(shopNo, 1);
    }

    queryOrderList(shopNo, pageindex) {
        const header = {"X-Client-ID": "123456"};
        if (pageindex == 1) {
            this.props.dispatch(reset("queryOrderList"));
        }
        this.props.dispatch(fetchPosts("queryOrderList", header, {
            "beginTime": this.getQueryDate(true),
            "endTime": this.getQueryDate(false),
            "openId": cookie.load("openId"),
            "pageindex": pageindex,
            "pagesize": PAGE_SIZE,
            "shopNo": shopNo
        }))
    }

    popCancel() {
        this.setState({
            isShowPop: false
        });
    }

    popConfirm(value) {
        this.setState({
            exportEmail: value
        });
        this._exportOrders();
    }

    checkBottom() {
        let scrollTop = document.body.scrollTop,
            innerHeight = window.innerHeight,
            scrollHeight = document.body.scrollHeight,
            pageindex = this.state.pageindex;
        if (scrollTop + innerHeight >= scrollHeight && !this.state.isLoadingMore
            && this.state.isCanLoadMore) {
            pageindex++;
            let shopNo = this.state.shopNo == 0 ? "" : this.state.shopNo;
            this.setState({
                isLoadingMore: true,
                pageindex: pageindex
            });
            this.queryOrderList(shopNo, pageindex);
        }
    }

    exportBill() {
        const header = {"X-Client-ID": "123456"};
        this.props.dispatch(reset("exportBill"));
        this.props.dispatch(fetchPosts("exportBill", header, {
            "beginTime": this.getQueryDate(true),
            "endTime": this.getQueryDate(false),
            "shopNo": (this.state.shopNo == 0 ? this.state.shopInfoList[0].shopNo : this.state.shopNo),
            "toMail": this.state.exportEmail,
            "userAccount": "",
        }));
    }

    getQueryDate(isStartDate) {
        let queryDate = cookie.load("queryDate");
        if (queryDate) {
            let {startYear, startMonth, startDay, endYear, endMonth, endDay} = queryDate;
            if (isStartDate) {
                return queryDateFormat(startYear, this.getDoubleDigit(startMonth), this.getDoubleDigit(startDay), isStartDate);
            } else {
                return queryDateFormat(endYear, this.getDoubleDigit(endMonth), this.getDoubleDigit(endDay), isStartDate);
            }

        } else {
            let date = new Date();
            return queryDateFormat(date.getFullYear(), this.getDoubleDigit(date.getMonth() + 1),
                this.getDoubleDigit(date.getDate()), isStartDate);
        }

    }

    getDoubleDigit(num) {
        return num < 10 ? "0" + num : num;
    }

    _changeQueryDate() {
        window.location.href = "/#/pay/selectDate?shopNo=" + this.state.shopNo;
    }

    _exportOrders() {
        if (!this.state.exportEmail) {
            this.setState({
                isShowPop: true
            });
            return;
        }
        this.setState({
            exportUnclickable: "unclickable",
            exportDisabled: "disabled"
        });
        this.exportBill();
    }
}

function dateFormat(year, month, day) {
    return year + "年" + month + "月" + day + "日";
}

function queryDateFormat(year, month, day, isStartDate) {
    return year + "-" + month + "-" + day + (isStartDate ? " 00:00" : " 23:59");
}

function mapStateToProps(state) {
    const {postsByApi} = state;
    const {
        isFetching,
        items: OrderList
    } = postsByApi["queryOrderList"] || {
        isFetching: false,
        items: {}
    };

    const {
        items: ExportBill
    } = postsByApi["exportBill"] || {
        isFetching: false,
        items: {}
    };
    return {
        isFetching,
        OrderList,
        ExportBill
    }
}

export default connect(mapStateToProps)(queryExportOrders);